/*
Copyright (C) 2018-2019 de4dot@gmail.com

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#if GAS || INTEL || MASM || NASM
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Iced.Intel;

namespace Iced.UnitTests.Intel.FormatterTests {
	static class SymbolResolverTestsReader {
		static class Dicts {
			// GENERATOR-BEGIN: Dicts
			// ⚠️This was generated by GENERATOR!🦹‍♂️
			internal static readonly Dictionary<string, SymbolFlags> ToSymbolFlags = new Dictionary<string, SymbolFlags>(2, StringComparer.Ordinal) {
				{ "rel", SymbolFlags.Relative },
				{ "signed", SymbolFlags.Signed },
			};
			// GENERATOR-END: Dicts
		}

		public static IEnumerable<SymbolResolverTestCase> ReadFile(string filename, HashSet<int> ignored) {
			Debug.Assert(File.Exists(filename));
			int lineNo = 0;
			int testCaseNo = 0;
			foreach (var line in File.ReadLines(filename)) {
				lineNo++;
				if (line.Length == 0 || line.StartsWith("#"))
					continue;

				SymbolResolverTestCase? tc;
				try {
					tc = ParseLine(line);
				}
				catch (Exception ex) {
					throw new Exception($"Invalid line {lineNo} ({filename}): {ex.Message}");
				}
				if (tc.HasValue)
					yield return tc.GetValueOrDefault();
				else
					ignored.Add(testCaseNo);
				testCaseNo++;
			}
		}

		static readonly char[] commaSeparator = new char[] { ',' };
		static readonly char[] spaceSeparator = new char[] { ' ' };
		static readonly char[] semicolonSeparator = new char[] { ';' };
		static readonly char[] barSeparator = new char[] { '|' };
		static SymbolResolverTestCase? ParseLine(string line) {
			var elems = line.Split(commaSeparator);
			const int SYM_RES_INDEX = 4;
			if (elems.Length < SYM_RES_INDEX)
				throw new Exception($"Invalid number of commas: {elems.Length - 1}");

			var bitness = NumberConverter.ToInt32(elems[0].Trim());
			var hexBytes = elems[1].Trim();
			var codeStr = elems[2].Trim();
			if (CodeUtils.IsIgnored(codeStr))
				return null;
			var code = ToEnumConverter.GetCode(codeStr);

			var options = new List<(OptionsProps property, object value)>();
			foreach (var part in elems[3].Split(spaceSeparator, StringSplitOptions.RemoveEmptyEntries))
				options.Add(OptionsParser.ParseOption(part));

			var symbolResults = new SymbolResultTestCase[elems.Length - SYM_RES_INDEX];
			for (int i = 0; i < symbolResults.Length; i++) {
				var symParts = elems[SYM_RES_INDEX + i].Split(semicolonSeparator);
				if (symParts.Length != 5)
					throw new Exception($"Invalid number of semicolons: {symParts.Length - 1}");

				var address = NumberConverter.ToUInt64(symParts[0].Trim());
				var symbolAddress = NumberConverter.ToUInt64(symParts[1].Trim());
				var addressSize = NumberConverter.ToInt32(symParts[2].Trim());
				var symbolParts = symParts[3].Split(barSeparator);

				MemorySize? memorySize = null;
				var flags = SymbolFlags.None;
				foreach (var value in symParts[4].Split(spaceSeparator, StringSplitOptions.RemoveEmptyEntries)) {
					if (Dicts.ToSymbolFlags.TryGetValue(value, out var f))
						flags |= f;
					else {
						if (!ToEnumConverter.TryMemorySize(value, out var memSize))
							throw new Exception($"Invalid value: {value}");
						memorySize = memSize;
					}
				}

				symbolResults[i] = new SymbolResultTestCase(address, symbolAddress, addressSize, flags, memorySize, symbolParts);
			}

			return new SymbolResolverTestCase(bitness, hexBytes, code, options.ToArray(), symbolResults);
		}
	}
}
#endif
